<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('specification_templates', function (Blueprint $table) {
            $table->id();
            $table->string('name')->comment('模板名称');
            $table->string('slug')->unique()->comment('模板别名');
            $table->text('description')->nullable()->comment('模板描述');
            $table->foreignId('category_id')->nullable()->constrained('categories')->onDelete('set null')->comment('适用分类');
            $table->json('attributes_config')->comment('属性配置JSON');
            $table->json('display_config')->nullable()->comment('显示配置JSON');
            $table->boolean('is_active')->default(true)->comment('是否启用');
            $table->boolean('is_default')->default(false)->comment('是否默认模板');
            $table->integer('sort_order')->default(0)->comment('排序权重');
            $table->json('meta_data')->nullable()->comment('元数据');
            $table->timestamps();
            
            // 索引
            $table->index(['category_id', 'is_active']);
            $table->index(['is_active', 'sort_order']);
            $table->index('slug');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        // 先删除 products 表的外键（如果 products 表存在）
        if (Schema::hasTable('products')) {
            Schema::table('products', function (Blueprint $table) {
                if (Schema::hasColumn('products', 'template_id')) {
                    $table->dropForeign(['template_id']);
                }
            });
        }
        
        Schema::dropIfExists('specification_templates');
    }
};
